const fs = require('fs')
const path = require('path')
const os = require('os')
function transformCss(scss) {
  const sass = require('sass')
  const result = sass.compileString(scss)
  let css = result.css
  let data = fs.readFileSync(path.resolve(__dirname, './css_rpx.json'), { encoding: 'utf8', flag: 'r' })
  const postcss2json = require('postcss2json')
  let json = postcss2json(css)
  // 这里的data是读取到的JSON内容
  const cssMap = JSON.parse(data)
  let cssTotal =os.EOL 
  json=json.reduce((pre,item) => {
    let { attributes } = item
    let rp = []
    let attrLeft = os.EOL
    let empty = true
    attributes.forEach(attr => {
      let { prop, value } = attr
      if (!prop) {
        return
      }
      let rule = `${prop}:${value}`
      let rpName = cssMap[rule]
      if (rpName) {
        attr.rpName = rpName
        rp.push(rpName)
      } else {
        empty = false
        attrLeft = attrLeft + rule + ';'+os.EOL
      }
    })
    cssTotal += `${item.selector}{${attrLeft}}${os.EOL}`
    item.rp = rp
    item.empty = empty
    let clsArrs = item.selector.replace(/[\r\n]/g,'').split(/,/)
    // console.log("🚀 ~ file: transform_css.js:39 ~ transformCss ~ clsArrs:", clsArrs);
    clsArrs.forEach(clsArr => {
      let tmp=JSON.parse(JSON.stringify(item));
      clsArr=clsArr.replace(/^\s*/,'');
      clsArr = clsArr.split(/\s+/)
      if (clsArr.length > 1) {
        clsArr = clsArr.map(item => {
          return item.replace(/^\./g, '')
        })
        tmp.name=clsArr[clsArr.length - 1].replace(/^\./, '')
        tmp.nest = true
        clsArr.splice(clsArr.length - 1, 1)
        tmp.clsArr = clsArr
      } else {
        tmp.name=tmp.selector.replace(/^\./, '')
        tmp.nest = false
        tmp.clsArr = []
      }
      pre.push(tmp);
    })
    return pre;
  },[])
  return { cssObj:json, cssLeft: cssTotal }
}

module.exports = { transformCss }